package com.tourlaid.mamagerment.action;

import com.tourlaid.mamagerment.util.DateUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.Date;
import java.util.UUID;

/**
 * Created by xiaoyongge on 2017/9/21.
 */
@RestController
@RequestMapping("/tld/admin/pthought2")
public class Test {

    @RequestMapping("/publish.json")
    public static String uploadBase64Image(String base64Data) throws Exception {

        String dataPrix = "";// 图片格式

        String data = "";// 图片内容

        if (StringUtils.isEmpty(base64Data)) {
            throw new Exception("上传失败，上传图片数据为空");
        } else {
            String[] d = base64Data.split("base64,");
            if (d != null && d.length == 2) {
                dataPrix = d[0];
                data = d[1];
            } else {
                throw new Exception("上传失败，数据不合法");
            }
        }

        String suffix = "";
        if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)
                || "data:image/jpg;".equalsIgnoreCase(dataPrix)) {// 编码的jpeg图片数据

            suffix = ".jpg";
        } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {// 编码的icon图片数据

            suffix = ".ico";
        } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {// 编码的gif图片数据

            suffix = ".gif";
        } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {// 编码的png图片数据

            suffix = ".png";
        } else {
            throw new Exception("上传图片格式不合法");
        }

        // 因为BASE64Decoder的jar问题，此处使用spring框架提供的工具包

        byte[] bs = Base64Utils.decodeFromString(data);
        //限制文件大小为4m以内

        if (bs.length > 8192) {
            throw new Exception("图片文件大小必须在1M以内！");
        }

        String today = DateUtil.getFormantDate(new Date(), "yyyyMMdd");// 以日期分组

        String realPath = "D:/tanlide-group/Tour-Laid-Manager/mamagerment/src/main/resources/img";// 获取项目根路径

        File file = new File(realPath);
        if (!file.exists()) {
            file.mkdir();
        }
        // String realPath = request.getServletContext().getRealPath("/upload");//报错

        String uuid = UUID.randomUUID().toString().replace("-", "");
        // 新文件名格式：项目根路径+upload+日期+uuid+后缀名

        String newFileName = new StringBuffer(uuid).append(".").append(suffix).toString();
        System.out.println("文件保存至：" + newFileName);
        try {
            // 使用apache提供的工具类操作流

            FileUtils.writeByteArrayToFile(new File(realPath + "/" + newFileName), bs);
        } catch (Exception ee) {
            throw new Exception("上传失败，写入文件失败，" + ee.getMessage());
        }
        System.out.println("-----------正常" + newFileName);
        return new StringBuffer(today).append("/").append(newFileName).toString();
    }

}
